package com.wskj.workbench.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ijpay.core.kit.AesUtil;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.PayKit;
import com.wskj.common.config.WxPayV3Bean;
import com.wskj.common.core.domain.entity.SysUser;
import com.wskj.common.core.domain.entity.TbUserTiktok;
import com.wskj.common.core.mybatisplus.core.ServicePlusImpl;
import com.wskj.common.core.page.PagePlus;
import com.wskj.common.core.page.TableDataInfo;
import com.wskj.common.utils.common.AssertUtils;
import com.wskj.common.utils.common.PageUtils;
import com.wskj.common.utils.common.SecurityUtils;
import com.wskj.system.service.ISysConfigService;
import com.wskj.system.service.ISysUserService;
import com.wskj.workbench.bo.app.AppTbUserJoinOrderAddBo;
import com.wskj.workbench.bo.app.AppTbUserJoinOrderDetailAddBo;
import com.wskj.workbench.bo.app.AppTbUserJoinOrderEditBo;
import com.wskj.workbench.bo.app.AppTbUserJoinOrderQueryBo;
import com.wskj.workbench.bo.web.TbUserJoinOrderAddBo;
import com.wskj.workbench.bo.web.TbUserJoinOrderEditBo;
import com.wskj.workbench.bo.web.TbUserJoinOrderQueryBo;
import com.wskj.workbench.domain.TbUserJoinOrder;
import com.wskj.workbench.domain.TbUserJoinOrderDetail;
import com.wskj.workbench.domain.TbUserWalletDetail;
import com.wskj.workbench.enums.*;
import com.wskj.workbench.mapper.TbUserJoinOrderMapper;
import com.wskj.workbench.service.ITbUserJoinOrderDetailService;
import com.wskj.workbench.service.ITbUserJoinOrderService;
import com.wskj.workbench.service.ITbUserTiktokService;
import com.wskj.workbench.service.ITbUserWalletDetailService;
import com.wskj.workbench.vo.app.AppTbUserJoinOrderDetailVo;
import com.wskj.workbench.vo.app.AppTbUserJoinOrderInfoVo;
import com.wskj.workbench.vo.app.AppTbUserJoinOrderVo;
import com.wskj.workbench.vo.app.AppZhaoshangDetailVo;
import com.wskj.workbench.vo.web.TbUserJoinOrderVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户入驻申请订单Service业务层处理
 *
 * @author wskj
 * @date 2024-09-25
 */
@Service
@AllArgsConstructor(onConstructor_ = {@Lazy})
@Slf4j
public class TbUserJoinOrderServiceImpl extends ServicePlusImpl<TbUserJoinOrderMapper, TbUserJoinOrder> implements ITbUserJoinOrderService {

    private final ITbUserJoinOrderDetailService tbUserJoinOrderDetailService;

    private final ISysConfigService sysConfigService;

    private final WxPayV3Bean wxPayV3Bean;

    private final ISysUserService sysUserService;

    private final ITbUserTiktokService tbUserTiktokService;

    private final ITbUserWalletDetailService walletDetailService;


    @Override
    public TbUserJoinOrderVo queryById(Long id) {

        TbUserJoinOrderVo tbUserJoinOrderVo = getVoById(id, TbUserJoinOrderVo.class);

        // 查询入驻详情
        List<TbUserJoinOrderDetail> list = tbUserJoinOrderDetailService.list(Wrappers.lambdaQuery(TbUserJoinOrderDetail.class)
                .eq(TbUserJoinOrderDetail::getJoinOrderId, id));
        tbUserJoinOrderVo.setDetailList(list);

        return tbUserJoinOrderVo;
    }

    @Override
    public TableDataInfo<TbUserJoinOrderVo> queryPageList(TbUserJoinOrderQueryBo bo) {
        PagePlus<TbUserJoinOrder, TbUserJoinOrderVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), TbUserJoinOrderVo.class);
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<TbUserJoinOrderVo> queryList(TbUserJoinOrderQueryBo bo) {
        return listVo(buildQueryWrapper(bo), TbUserJoinOrderVo.class);
    }

    private LambdaQueryWrapper<TbUserJoinOrder> buildQueryWrapper(TbUserJoinOrderQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TbUserJoinOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getUserType()), TbUserJoinOrder::getUserType, bo.getUserType());
        lqw.like(StrUtil.isNotBlank(bo.getRealName()), TbUserJoinOrder::getRealName, bo.getRealName());
        lqw.eq(StrUtil.isNotBlank(bo.getSex()), TbUserJoinOrder::getSex, bo.getSex());
        lqw.eq(StrUtil.isNotBlank(bo.getCardNo()), TbUserJoinOrder::getCardNo, bo.getCardNo());
        lqw.eq(StrUtil.isNotBlank(bo.getPhoneNumber()), TbUserJoinOrder::getPhoneNumber, bo.getPhoneNumber());
        lqw.eq(StrUtil.isNotBlank(bo.getPassword()), TbUserJoinOrder::getPassword, bo.getPassword());
        lqw.eq(StrUtil.isNotBlank(bo.getOrderStatus()), TbUserJoinOrder::getOrderStatus, bo.getOrderStatus());
        lqw.eq(bo.getOrderPrice() != null, TbUserJoinOrder::getOrderPrice, bo.getOrderPrice());
        lqw.eq(StrUtil.isNotBlank(bo.getInviteCode()), TbUserJoinOrder::getInviteCode, bo.getInviteCode());
        lqw.eq(StrUtil.isNotBlank(bo.getReviewReason()), TbUserJoinOrder::getReviewReason, bo.getReviewReason());
        lqw.eq(StrUtil.isNotBlank(bo.getDelFlag()), TbUserJoinOrder::getDelFlag, bo.getDelFlag());


        // 如果不是超级管理员 需要查询所有下级用户列表
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {

            SysUser sysUser = sysUserService.selectUserById(SecurityUtils.getUserId());

            String inviteFullCode = sysUser.getInviteFullCode() + sysUser.getInviteCode();

            // 所有的用户下级
            List<Long> userIds = sysUserService.list(Wrappers.lambdaQuery(SysUser.class).likeRight(SysUser::getInviteFullCode, inviteFullCode)).stream()
                    .map(SysUser::getUserId).collect(Collectors.toList());


            if (ObjectUtil.isEmpty(userIds)) {
                lqw.in(TbUserJoinOrder::getUserId, 0);

            } else {
                lqw.in(ObjectUtil.isNotEmpty(userIds), TbUserJoinOrder::getUserId, userIds);
            }
        }
        lqw.orderByDesc(TbUserJoinOrder::getCreateTime);


        return lqw;
    }

    @Override
    public Boolean insertByAddBo(TbUserJoinOrderAddBo bo) {
        TbUserJoinOrder add = BeanUtil.toBean(bo, TbUserJoinOrder.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(TbUserJoinOrderEditBo bo) {
        TbUserJoinOrder update = BeanUtil.toBean(bo, TbUserJoinOrder.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(TbUserJoinOrder entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    @Override
    public String importTbUserJoinOrder(List<TbUserJoinOrderVo> tbUserJoinOrderList) {
        AssertUtils.isTrue(CollectionUtils.isNotEmpty(tbUserJoinOrderList), "导入数据不能为空");
        int successNum = 0;
        for (TbUserJoinOrderVo tbUserJoinOrder : tbUserJoinOrderList) {
            TbUserJoinOrder add = BeanUtil.toBean(tbUserJoinOrder, TbUserJoinOrder.class);
            save(add);
            successNum++;
        }
        String msg = String.format("导入完成，共计 %d 条数据，成功 %d 条！", tbUserJoinOrderList.size(), successNum);
        if (successNum != tbUserJoinOrderList.size()) {
            msg = msg + String.format("失败 %d 条！", tbUserJoinOrderList.size() - successNum);
        }
        return msg;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppTbUserJoinOrderVo apply(AppTbUserJoinOrderAddBo bo) throws Exception {


        AppTbUserJoinOrderVo appTbUserJoinOrderVo = new AppTbUserJoinOrderVo();

        boolean checkTel = Validator.isMobile(bo.getPhoneNumber());
        AssertUtils.isTrue(checkTel, "手机号不正确");


        // 判断手机号是否已被使用
        SysUser dbSysUser = sysUserService.getOne(Wrappers.lambdaQuery(SysUser.class)
                .eq(SysUser::getPhoneNumber, bo.getPhoneNumber()).in(SysUser::getStatus, SysUserStatusEnum.NORMAL.getValue(),
                        SysUserStatusEnum.STOP.getValue()).last("limit 1"));
        AssertUtils.isNull(dbSysUser, "该手机号已被注册");


        // 查询邀请码
        SysUser dbUser = sysUserService.getOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getInviteCode, bo.getInviteCode()));
        AssertUtils.notNull(dbUser, "邀请码不合法");


        AssertUtils.isTrue(IdcardUtil.isValidCard(bo.getCardNo()), "身份证号不合法");
        AssertUtils.isTrue(bo.getPassword().equals(bo.getAgainPassword()), "两次输入的密码不一致");


        // 判断用户之前是不是有申请过的待审核的记录 如果有的话 删除掉之前的申请记录
        TbUserJoinOrder one = getOne(Wrappers.lambdaQuery(TbUserJoinOrder.class)
                .eq(TbUserJoinOrder::getPhoneNumber, bo.getPhoneNumber())
                .eq(TbUserJoinOrder::getOrderStatus, UserJoinOrderOrderStatusEnum.YIZHIFU.getValue())
                .last("limit 1"));
        if (ObjectUtil.isNotEmpty(one)) {
            // 删除申请单明细数据
            tbUserJoinOrderDetailService.remove(Wrappers.lambdaQuery(TbUserJoinOrderDetail.class).eq(TbUserJoinOrderDetail::getJoinOrderId,
                    one.getId()));
            // 删除申请单数据
            removeById(one.getId());
        }


        TbUserJoinOrder tbUserJoinOrder = BeanUtil.copyProperties(bo, TbUserJoinOrder.class);

        // 查询该手机号以前相同的身份是否支付过 如果支付过 则不需要再次支付
//        long countNumber = count(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getPhoneNumber, bo.getPhoneNumber())
//                .eq(TbUserJoinOrder::getUserType, bo.getUserType()).in(TbUserJoinOrder::getOrderStatus,
//                        UserJoinOrderOrderStatusEnum.YIZHIFU.getValue(), UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue(),
//                        UserJoinOrderOrderStatusEnum.SHENHEBUTONGGUO.getValue()));
//
//        if (countNumber == 0) {
//            // 未支付状态
//            tbUserJoinOrder.setOrderStatus(UserJoinOrderOrderStatusEnum.WEIZHIFU.getValue());
//        } else {
        tbUserJoinOrder.setOrderStatus(UserJoinOrderOrderStatusEnum.YIZHIFU.getValue());
        // }


        BigDecimal orderPrice = BigDecimal.ZERO;
        if (bo.getUserType().equals("01")) {
            orderPrice = new BigDecimal(sysConfigService.selectConfigByKey("zhubo_price"));
        } else if (bo.getUserType().equals("02")) {
            orderPrice = new BigDecimal(sysConfigService.selectConfigByKey("tuanzhang_price"));
        } else if (bo.getUserType().equals("03")) {
            orderPrice = new BigDecimal(sysConfigService.selectConfigByKey("fengongsi_price"));
        }

        // 订单金额
        tbUserJoinOrder.setOrderPrice(orderPrice);


        // 生成订单编号
        String format = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        String numbers = RandomUtil.randomNumbers(5);
        String orderNo = "AP" + format + numbers;
        tbUserJoinOrder.setOrderNo(orderNo);

        // 根据jsCode获取openId

        // 配置请求参数
//        Map<String, String> param = new HashMap<>();
//        param.put("appid", wxPayV3Bean.getAppId());
//        param.put("secret", wxPayV3Bean.getAppSecret());
//        param.put("js_code", bo.getWxCode());
//        param.put("grant_type", WechatUtils.WX_LOGIN_GRANT_TYPE);
//        param.put("scope", "snsapi_userinfo");
//        // 发送请求
//        String wxResult = HttpUtils.sendGet(WechatUtils.WX_LOGIN_URL, param);
//        log.info("微信授权获取的结果--------》{}", wxResult);
//        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(wxResult);
//        // 返回微信小程序openId
//        String openId = jsonObject.get("openid").toString();
//        tbUserJoinOrder.setOpenId(openId);
        save(tbUserJoinOrder);


        // 抖音号列表
        List<AppTbUserJoinOrderDetailAddBo> tiktokList = bo.getTiktokList();
        List<TbUserJoinOrderDetail> tiktoks = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(tiktokList)) {
            for (AppTbUserJoinOrderDetailAddBo appTbUserTiktokAddBo : tiktokList) {
                TbUserJoinOrderDetail tbUserJoinOrderDetail = BeanUtil.copyProperties(appTbUserTiktokAddBo, TbUserJoinOrderDetail.class);

                // 查询抖音uid是不是已经绑定到其他用户名下
                long count = tbUserTiktokService.count(Wrappers.lambdaQuery(TbUserTiktok.class).eq(TbUserTiktok::getTikUid,
                        tbUserJoinOrderDetail.getTikUid()));

                AssertUtils.isTrue(count == 0, "抖音uid【" + tbUserJoinOrderDetail.getTikUid() + "】,已被其他用户绑定,不能重复绑定");

                tbUserJoinOrderDetail.setJoinOrderId(tbUserJoinOrder.getId());
                tiktoks.add(tbUserJoinOrderDetail);
            }
            if (ObjectUtil.isNotEmpty(tiktoks)) {
                tbUserJoinOrderDetailService.saveAll(tiktoks);
            }
        }

        // 是否需要支付
//        if (countNumber == 0) {
//            appTbUserJoinOrderVo.setNeedPay("1");
//
//
//            // 应付金额转换为分
//            int fen = orderPrice.movePointRight(2).intValue();
//
//
//            Payer payer = new Payer();
//            payer.setOpenid(openId);
//
//            UnifiedOrderModel unifiedOrderModel = new UnifiedOrderModel()
//                    .setAppid(wxPayV3Bean.getAppId())
//                    .setMchid(wxPayV3Bean.getMchId())
//                    .setDescription("用户入驻")
//                    .setOut_trade_no(orderNo)
//                    .setAttach("微信支付方式支付")
//                    .setNotify_url(wxPayV3Bean.getDomain().concat(wxPayV3Bean.getNotifyUrl()))
//                    .setAmount(new Amount().setTotal(fen))
//                    .setPayer(payer);
//
//            log.info("统一下单参数 {}", JSONUtil.toJsonStr(unifiedOrderModel));
//
//            IJPayHttpResponse response = WxPayApi.v3(
//                    RequestMethod.POST,
//                    WxDomain.CHINA.toString(),
//                    WxApiType.JS_API_PAY.toString(),
//                    wxPayV3Bean.getMchId(),
//                    getSerialNumber(),
//                    null,
//                    wxPayV3Bean.getKeyPath(),
//                    JSONUtil.toJsonStr(unifiedOrderModel)
//            );
//            log.info("统一下单响应 {}", response);
//
//            JSONObject entries = JSONUtil.parseObj(response.getBody());
//            String prepayId = entries.getStr("prepay_id");
//            log.info("预支付的id为--------》{}", prepayId);
//            Map<String, String> orderMap = WxPayKit.jsApiCreateSign(wxPayV3Bean.getAppId(), prepayId, wxPayV3Bean.getKeyPath());
//            appTbUserJoinOrderVo.setOrderInfo(orderMap);
//
//
//        } else {
        appTbUserJoinOrderVo.setNeedPay("2");
        // }
        return appTbUserJoinOrderVo;
    }

    private String getSerialNumber() {
        // 获取证书序列号
        X509Certificate certificate = PayKit.getCertificate(FileUtil.getInputStream(wxPayV3Bean.getCertPath()));
        String serialNo = certificate.getSerialNumber().toString(16).toUpperCase();
        log.info("证书系列号为--->{}", serialNo);
        return serialNo;
    }


    @Override
    public void wxPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> map = new HashMap<>(12);

        String timestamp = request.getHeader("Wechatpay-Timestamp");
        String nonce = request.getHeader("Wechatpay-Nonce");
        String serialNo = request.getHeader("Wechatpay-Serial");
        String signature = request.getHeader("Wechatpay-Signature");

        log.info("timestamp:{} nonce:{} serialNo:{} signature:{}", timestamp, nonce, serialNo, signature);
        String result = HttpKit.readData(request);
        log.info("支付通知密文 {}", result);

        // 需要通过证书序列号查找对应的证书，verifyNotify 中有验证证书的序列号


        JSONObject resultObject = JSONUtil.parseObj(result);
        JSONObject resource = resultObject.getJSONObject("resource");
        String cipherText = resource.getStr("ciphertext");
        String nonceStr = resource.getStr("nonce");
        String associatedData = resource.getStr("associated_data");

        AesUtil aesUtil = new AesUtil(wxPayV3Bean.getApiKey3().getBytes(StandardCharsets.UTF_8));
        // 密文解密
        String plainText = aesUtil.decryptToString(
                associatedData.getBytes(StandardCharsets.UTF_8),
                nonceStr.getBytes(StandardCharsets.UTF_8),
                cipherText
        );


        log.info("支付通知明文 {}", plainText);

        // 修改订单状态为已支付
        JSONObject jsonObject = JSONUtil.parseObj(plainText);
        String orderNo = jsonObject.getStr("out_trade_no");

        handleOrder(orderNo);

        if (StrUtil.isNotEmpty(plainText)) {
            response.setStatus(200);
            map.put("code", "SUCCESS");
            map.put("message", "SUCCESS");
        } else {
            response.setStatus(500);
            map.put("code", "ERROR");
            map.put("message", "签名错误");
        }
        response.setHeader("Content-type", ContentType.JSON.toString());
        response.getOutputStream().write(JSONUtil.toJsonStr(map).getBytes(StandardCharsets.UTF_8));
        response.flushBuffer();

    }

    public void handleOrder(String orderNo) {
        TbUserJoinOrder tbUserJoinOrder = getOne(new LambdaQueryWrapper<TbUserJoinOrder>().eq(TbUserJoinOrder::getOrderNo, orderNo));

        // 获取订单的状态
        log.info("获取到的订单状态为------》{}", tbUserJoinOrder.getOrderStatus());

        // 如果没有处理过此通知
        if (UserJoinOrderOrderStatusEnum.WEIZHIFU.getValue().equals(tbUserJoinOrder.getOrderStatus())) {
            tbUserJoinOrder.setOrderStatus(UserJoinOrderOrderStatusEnum.YIZHIFU.getValue());
            updateById(tbUserJoinOrder);
            log.info("修改完订单后的状态为--------》{}", tbUserJoinOrder.getOrderStatus());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean audit(TbUserJoinOrderEditBo bo) {
        TbUserJoinOrder tbUserJoinOrder = getById(bo.getId());
        tbUserJoinOrder.setOrderStatus(bo.getOrderStatus());
        tbUserJoinOrder.setReviewReason(bo.getReviewReason());
        boolean result = updateById(tbUserJoinOrder);

        // 如果userId为空 则证明为新入住的请求 则创建用户和分佣
        if (ObjectUtil.isEmpty(bo.getUserId())) {


            // 如果审核通过后 则创建用户
            if (bo.getOrderStatus().equals(UserJoinOrderOrderStatusEnum.SHENHEBUTONGGUO.getValue())) {
                return true;
            }


            // 注册用户
            SysUser sysUser = new SysUser();
            sysUser.setUserName(tbUserJoinOrder.getPhoneNumber());
            sysUser.setPhoneNumber(tbUserJoinOrder.getPhoneNumber());
            sysUser.setUserType(tbUserJoinOrder.getUserType());
            sysUser.setRealName(tbUserJoinOrder.getRealName());
            sysUser.setSex(tbUserJoinOrder.getSex());
            sysUser.setCardNo(tbUserJoinOrder.getCardNo());
            // 微信id
            sysUser.setWxUid(tbUserJoinOrder.getWxCode());
            // 微信头像
            sysUser.setAvatar(tbUserJoinOrder.getWxAvatar());
            // 微信昵称
            sysUser.setNickName(tbUserJoinOrder.getWxNickName());

            // 生成自己的邀请码
            while (true) {
                String yqcode = RandomUtil.randomNumbers(6);
                List<SysUser> list = sysUserService.list(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getInviteCode, yqcode));
                if (CollectionUtil.isEmpty(list)) {
                    sysUser.setInviteCode(yqcode);
                    break;
                }
            }
            // 父级码
            String inviteFullCode;
            // 前端是否传递邀请码
            String inviteCode = tbUserJoinOrder.getInviteCode();

            // 查询邀请人
            SysUser yaoqingUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getInviteCode, inviteCode));
            AssertUtils.isTrue(ObjectUtil.isNotEmpty(yaoqingUser), "邀请码不合法");

            sysUser.setZhiUserId(yaoqingUser.getUserId());
            sysUser.setRecommendCode(sysUser.getInviteCode());

            inviteFullCode = yaoqingUser.getInviteFullCode() + yaoqingUser.getInviteCode();

            sysUser.setInviteFullCode(inviteFullCode);

            // 密码
            sysUser.setPassword(SecurityUtils.encryptPassword(tbUserJoinOrder.getPassword()));


            sysUser.setWxUid(tbUserJoinOrder.getOpenId());

            // 已认证
            sysUser.setAuthStatus("1");

            sysUserService.save(sysUser);


            // 补充用户信息
            tbUserJoinOrder.setUserId(sysUser.getUserId());
            updateById(tbUserJoinOrder);


            List<TbUserJoinOrderDetail> list = tbUserJoinOrderDetailService.list(Wrappers.lambdaQuery(TbUserJoinOrderDetail.class)
                    .eq(TbUserJoinOrderDetail::getJoinOrderId, bo.getId()));

            // 抖音号列表
            List<TbUserTiktok> tiktoks = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(list)) {
                for (TbUserJoinOrderDetail tbUserJoinOrderDetail : list) {
                    TbUserTiktok tbUserTiktok = BeanUtil.copyProperties(tbUserJoinOrderDetail, TbUserTiktok.class, "id");
                    tbUserTiktok.setUserId(sysUser.getUserId());
                    tiktoks.add(tbUserTiktok);
                }
                if (ObjectUtil.isNotEmpty(tiktoks)) {
                    tbUserTiktokService.saveAll(tiktoks);
                }
            }
            // 给直接上级分佣和上上级分佣
            handleComm(sysUser, yaoqingUser, tbUserJoinOrder);


        } else {
            SysUser sysUser = sysUserService.getById(tbUserJoinOrder.getUserId());
            sysUser.setUserType(tbUserJoinOrder.getUserType());
            if (bo.getOrderStatus().equals(UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue())) {
                sysUser.setAuthStatus("1");
            } else {
                sysUser.setAuthStatus("2");
            }
            sysUserService.updateById(sysUser);


            // 如果审核不通过 直接不处理
            if (bo.getOrderStatus().equals(UserJoinOrderOrderStatusEnum.SHENHEBUTONGGUO.getValue())) {
                return true;
            }


            // 删除掉之前抖音号列表
            tbUserTiktokService.remove(Wrappers.lambdaQuery(TbUserTiktok.class).eq(TbUserTiktok::getUserId, sysUser.getUserId()));


            List<TbUserJoinOrderDetail> list = tbUserJoinOrderDetailService.list(Wrappers.lambdaQuery(TbUserJoinOrderDetail.class)
                    .eq(TbUserJoinOrderDetail::getJoinOrderId, bo.getId()));

            // 抖音号列表
            List<TbUserTiktok> tiktoks = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(list)) {
                for (TbUserJoinOrderDetail tbUserJoinOrderDetail : list) {
                    TbUserTiktok tbUserTiktok = BeanUtil.copyProperties(tbUserJoinOrderDetail, TbUserTiktok.class, "id");
                    tbUserTiktok.setUserId(sysUser.getUserId());
                    tiktoks.add(tbUserTiktok);
                }
                if (ObjectUtil.isNotEmpty(tiktoks)) {
                    tbUserTiktokService.saveAll(tiktoks);
                }
            }

            // 此次修改并且提升了身份
            String now = tbUserJoinOrder.getUserType().substring(1);
            String yuanlai1 = sysUser.getUserType().substring(1);
            if (Integer.valueOf(now) > Integer.valueOf(yuanlai1)) {

                // 查询邀请人
                SysUser yaoqingUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getInviteCode, tbUserJoinOrder.getInviteCode()));
                AssertUtils.isTrue(ObjectUtil.isNotEmpty(yaoqingUser), "邀请码不合法");

                // 给直接上级分佣和上上级分佣
                handleComm(sysUser, yaoqingUser, tbUserJoinOrder);

            }


        }
        return result;
    }

    private void handleComm(SysUser contributorUser, SysUser sysUser, TbUserJoinOrder tbUserJoinOrder) {
        String userType = sysUser.getUserType();
        // 如果上级是主播 则只有佣金提成 没有招商提成
        if (userType.equals(UserTypeEnum.ZHUBO.getValue())) {


        } else if (userType.equals(UserTypeEnum.TUANZHANG.getValue())) {

            // 如果小于等于3个并且本次邀请的用户是个主播 则直接拿主播的钱
            if (tbUserJoinOrder.getUserType().equals(UserTypeEnum.ZHUBO.getValue())) {

                // 查询直推的下级
                List<SysUser> xiaji = sysUserService.list(Wrappers.lambdaQuery(SysUser.class)
                        .eq(SysUser::getZhiUserId, sysUser.getUserId())
                        .eq(SysUser::getDeleted, 0));

                // 已推广主播的数量+过去是主播但是身份升级了
                int zhiboCount = 0;
                for (SysUser user : xiaji) {

                    // 如果是主播
                    if (UserTypeEnum.ZHUBO.getValue().equals(user.getUserType())) {
                        zhiboCount = zhiboCount + 1;
                    } else if (UserTypeEnum.TUANZHANG.getValue().equals(user.getUserType())) {
                        // 查询他曾经有没有主播身份 如果有的话 证明升级过身份
                        long count = count(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getUserType,
                                UserTypeEnum.ZHUBO.getValue()).eq(TbUserJoinOrder::getOrderStatus,
                                UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue()).eq(TbUserJoinOrder::getUserId, user.getUserId()));
                        if (count > 0) {
                            zhiboCount = zhiboCount + 1;
                        }
                    } else if (UserTypeEnum.FENGONGSI.getValue().equals(user.getUserType())) {
                        // 查询他曾经有没有主播身份 如果有的话 证明升级过身份
                        long count = count(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getUserType,
                                UserTypeEnum.ZHUBO.getValue()).eq(TbUserJoinOrder::getOrderStatus,
                                UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue()).eq(TbUserJoinOrder::getUserId, user.getUserId()));
                        if (count > 0) {
                            zhiboCount = zhiboCount + 1;
                        }
                    }
                }


                // 查询团长有几个主播招商名额
                String zbzs = sysConfigService.selectConfigByKey("tz_zs_me");


                if (zhiboCount <= Integer.valueOf(zbzs)) {
                    BigDecimal zhubo = new BigDecimal(sysConfigService.selectConfigByKey("zhubo_price"));
                    sysUser.setTotalAmount(sysUser.getTotalAmount().add(zhubo));
                    sysUser.setPromoAmount(sysUser.getPromoAmount().add(zhubo));
                    sysUserService.updateById(sysUser);
                    handleWallet(contributorUser, UserWalletDetailRecommendTypeEnum.ZHITUI.getValue(), sysUser, tbUserJoinOrder, zhubo);
                    return;
                }
            }

            // 其它情况 则按比例计算招商提成

            // 如果是团长
            String tuanzhangZhituiPercent = sysConfigService.selectConfigByKey("tuanzhang_zhitui_percent");
            // 直接上级提成
            BigDecimal zhijiticheng = tbUserJoinOrder.getOrderPrice().multiply(new BigDecimal(tuanzhangZhituiPercent)).divide(new BigDecimal(100))
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            sysUser.setTotalAmount(sysUser.getTotalAmount().add(zhijiticheng));
            sysUser.setPromoAmount(sysUser.getPromoAmount().add(zhijiticheng));
            sysUserService.updateById(sysUser);
            // 钱包明细增加
            handleWallet(contributorUser, UserWalletDetailRecommendTypeEnum.ZHITUI.getValue(), sysUser, tbUserJoinOrder, zhijiticheng);
            // 查询上上级
            SysUser parentUser = sysUserService.getById(sysUser.getZhiUserId());
            if (ObjectUtil.isNotEmpty(parentUser)) {
                if (parentUser.getUserType().equals(UserTypeEnum.TUANZHANG.getValue())) {
                    // 间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("tuanzhang_jiantui_percent");
                    // 间接上级提成
                    BigDecimal shangjitiacheng = tbUserJoinOrder.getOrderPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);

                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);

                    // 钱包明细增加
                    handleWallet(contributorUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tbUserJoinOrder, shangjitiacheng);
                } else if (parentUser.getUserType().equals(UserTypeEnum.FENGONGSI.getValue())) {
                    // 分公司间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("fgszstcjtbl");
                    // 间接上级提成
                    BigDecimal shangjitiacheng = tbUserJoinOrder.getOrderPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);
                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);
                    // 钱包明细增加
                    handleWallet(contributorUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tbUserJoinOrder, shangjitiacheng);
                }
            }


        } else if (userType.equals(UserTypeEnum.FENGONGSI.getValue())) {
            // 如果邀请的是个主播
            if (UserTypeEnum.ZHUBO.getValue().equals(tbUserJoinOrder.getUserType())) {

                // 查询直推的下级
                List<SysUser> xiaji = sysUserService.list(Wrappers.lambdaQuery(SysUser.class)
                        .eq(SysUser::getZhiUserId, sysUser.getUserId())
                        .eq(SysUser::getDeleted, 0));


                // 已推广主播的数量+过去是主播但是身份升级了
                int zhiboCount = 0;
                for (SysUser user : xiaji) {

                    // 如果是主播
                    if (UserTypeEnum.ZHUBO.getValue().equals(user.getUserType())) {
                        zhiboCount = zhiboCount + 1;
                    } else if (UserTypeEnum.TUANZHANG.getValue().equals(user.getUserType())) {
                        // 查询他曾经有没有主播身份 如果有的话 证明升级过身份
                        long count = count(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getUserType,
                                UserTypeEnum.ZHUBO.getValue()).eq(TbUserJoinOrder::getOrderStatus,
                                UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue()).eq(TbUserJoinOrder::getUserId, user.getUserId()));
                        if (count > 0) {
                            zhiboCount = zhiboCount + 1;
                        }
                    } else if (UserTypeEnum.FENGONGSI.getValue().equals(user.getUserType())) {
                        // 查询他曾经有没有主播身份 如果有的话 证明升级过身份
                        long count = count(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getUserType,
                                UserTypeEnum.ZHUBO.getValue()).eq(TbUserJoinOrder::getOrderStatus,
                                UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue()).eq(TbUserJoinOrder::getUserId, user.getUserId()));
                        if (count > 0) {
                            zhiboCount = zhiboCount + 1;
                        }
                    }
                }

                // 查询分公司邀请了几个直推的主播
                String fgszbzsme = sysConfigService.selectConfigByKey("fgs_zb_zs_me");
                if ((zhiboCount <= Integer.valueOf(fgszbzsme))) {
                    BigDecimal zhubo = new BigDecimal(sysConfigService.selectConfigByKey("zhubo_price"));
                    sysUser.setTotalAmount(sysUser.getTotalAmount().add(zhubo));
                    sysUser.setPromoAmount(sysUser.getPromoAmount().add(zhubo));
                    sysUserService.updateById(sysUser);
                    handleWallet(contributorUser, UserWalletDetailRecommendTypeEnum.ZHITUI.getValue(), sysUser, tbUserJoinOrder, zhubo);
                    return;
                }
            } else if (UserTypeEnum.TUANZHANG.getValue().equals(tbUserJoinOrder.getUserType())) {  // 如果邀请的是个团长


                // 查询直推的下级
                List<SysUser> xiaji = sysUserService.list(Wrappers.lambdaQuery(SysUser.class)
                        .eq(SysUser::getZhiUserId, sysUser.getUserId())
                        .eq(SysUser::getDeleted, 0));


                // 已推广团长的数量+过去是团长但是身份升级了
                int tuanzhangCount = 0;
                for (SysUser user : xiaji) {
                    // 如果是主播
                    if (UserTypeEnum.ZHUBO.getValue().equals(user.getUserType())) {

                    } else if (UserTypeEnum.TUANZHANG.getValue().equals(user.getUserType())) {
                        tuanzhangCount = tuanzhangCount + 1;
                    } else if (UserTypeEnum.FENGONGSI.getValue().equals(user.getUserType())) {
                        // 查询他曾经有没有团长身份 如果有的话 证明升级过身份
                        long count = count(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getUserType,
                                UserTypeEnum.TUANZHANG.getValue()).eq(TbUserJoinOrder::getOrderStatus,
                                UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue()).eq(TbUserJoinOrder::getUserId, user.getUserId()));
                        if (count > 0) {
                            tuanzhangCount = tuanzhangCount + 1;
                        }
                    }
                }


                // 查询分公司有几个团长招商名额
                String fgstzzsme = sysConfigService.selectConfigByKey("fgs_tz_zs_me");
                // 如果小于等于5个并且本次邀请的用户是个团长
                if (tuanzhangCount <= Integer.valueOf(fgstzzsme)) {
                    BigDecimal tuahznag = new BigDecimal(sysConfigService.selectConfigByKey("tuanzhang_price"));
                    sysUser.setTotalAmount(sysUser.getTotalAmount().add(tuahznag));
                    sysUser.setPromoAmount(sysUser.getPromoAmount().add(tuahznag));
                    sysUserService.updateById(sysUser);
                    handleWallet(contributorUser, UserWalletDetailRecommendTypeEnum.ZHITUI.getValue(), sysUser, tbUserJoinOrder, tuahznag);
                    return;
                }
            }
            // 其它情况 则按比例计算招商提成

            // 查询分公司直推比例
            String fengongsiZhituiPercent = sysConfigService.selectConfigByKey("fgszstgztbl");
            // 直接上级提成
            BigDecimal zhijiticheng = tbUserJoinOrder.getOrderPrice().multiply(new BigDecimal(fengongsiZhituiPercent)).divide(new BigDecimal(100))
                    .setScale(2, BigDecimal.ROUND_HALF_UP);

            sysUser.setTotalAmount(sysUser.getTotalAmount().add(zhijiticheng));
            sysUser.setPromoAmount(sysUser.getPromoAmount().add(zhijiticheng));
            sysUserService.updateById(sysUser);

            // 钱包明细增加
            handleWallet(contributorUser, UserWalletDetailRecommendTypeEnum.ZHITUI.getValue(), sysUser, tbUserJoinOrder, zhijiticheng);


            // 查询上上级
            SysUser parentUser = sysUserService.getById(sysUser.getZhiUserId());
            if (ObjectUtil.isNotEmpty(parentUser)) {
                if (parentUser.getUserType().equals(UserTypeEnum.TUANZHANG.getValue())) {
                    // 间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("tuanzhang_jiantui_percent");
                    // 间接上级提成
                    BigDecimal shangjitiacheng = tbUserJoinOrder.getOrderPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);

                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);

                    // 钱包明细增加
                    handleWallet(contributorUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tbUserJoinOrder, shangjitiacheng);
                } else if (parentUser.getUserType().equals(UserTypeEnum.FENGONGSI.getValue())) {


                    // 分公司间推比例
                    String jianjiePercent = sysConfigService.selectConfigByKey("fgszstcjtbl");
                    // 间接上级提成
                    BigDecimal shangjitiacheng = tbUserJoinOrder.getOrderPrice().multiply(new BigDecimal(jianjiePercent)).divide(new BigDecimal(100))
                            .setScale(2, BigDecimal.ROUND_HALF_UP);

                    parentUser.setTotalAmount(parentUser.getTotalAmount().add(shangjitiacheng));
                    parentUser.setPromoAmount(parentUser.getPromoAmount().add(shangjitiacheng));
                    sysUserService.updateById(parentUser);

                    // 钱包明细增加
                    handleWallet(contributorUser, UserWalletDetailRecommendTypeEnum.JIANTUI.getValue(), parentUser, tbUserJoinOrder, shangjitiacheng);
                }
            }
        }

    }


    private void handleWallet(SysUser contributorUser, String recommendType, SysUser sysUser, TbUserJoinOrder tbUserJoinOrder, BigDecimal price) {
        if (price.compareTo(BigDecimal.ZERO) > 0) {
            TbUserWalletDetail tbUserWalletDetail = new TbUserWalletDetail();
            tbUserWalletDetail.setUserId(sysUser.getUserId());
            tbUserWalletDetail.setPhoneNumber(sysUser.getPhoneNumber());
            tbUserWalletDetail.setRealName(sysUser.getRealName());
            if (tbUserJoinOrder.getUserType().equals(UserTypeEnum.ZHUBO.getValue())) {
                tbUserWalletDetail.setDetailType(UserWalletDetailDetailTypeEnum.TUIGUANGZHUBO.getValue());
            } else if (tbUserJoinOrder.getUserType().equals(UserTypeEnum.TUANZHANG.getValue())) {
                tbUserWalletDetail.setDetailType(UserWalletDetailDetailTypeEnum.TUIGUANGTUANZHANG.getValue());
            } else if (tbUserJoinOrder.getUserType().equals(UserTypeEnum.FENGONGSI.getValue())) {
                tbUserWalletDetail.setDetailType(UserWalletDetailDetailTypeEnum.TUIGUANGFENGONGSI.getValue());
            }
            tbUserWalletDetail.setDetailPrice(price);

            // 如果贡献人不为空
            if (ObjectUtil.isNotEmpty(contributorUser)) {
                tbUserWalletDetail.setRecommendId(contributorUser.getUserId());
                tbUserWalletDetail.setRecommendName(contributorUser.getRealName());
                tbUserWalletDetail.setRecommendPhone(contributorUser.getPhoneNumber());
                tbUserWalletDetail.setRecommendAvatar(contributorUser.getAvatar());
            }

            tbUserWalletDetail.setRecommendType(recommendType);

            walletDetailService.save(tbUserWalletDetail);
        }
    }

    @Override
    public void autoCancel() {
        String minute = sysConfigService.selectConfigByKey("auto_calcel");
        List<TbUserJoinOrder> expireList = baseMapper.getExpireList(minute);
        for (TbUserJoinOrder tbUserJoinOrder : expireList) {
            tbUserJoinOrder.setOrderStatus(UserJoinOrderOrderStatusEnum.YIQUXIAO.getValue());
        }
        if (ObjectUtil.isNotEmpty(expireList)) {
            updateBatchById(expireList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppTbUserJoinOrderVo updateAuth(AppTbUserJoinOrderEditBo bo) throws Exception {

        AppTbUserJoinOrderVo appTbUserJoinOrderVo = new AppTbUserJoinOrderVo();

        SysUser sysUser = sysUserService.getById(SecurityUtils.getUserId());

        // 判断用户之前是否有正在审核中的单子 如果有的话不能再次修改信息
        long count1 = count(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getOrderStatus,
                UserJoinOrderOrderStatusEnum.YIZHIFU.getValue()).eq(TbUserJoinOrder::getUserId, sysUser.getUserId()));
        AssertUtils.isTrue(count1 == 0, "有正在审核中的订单,不能重复提交");


        // 修改认证信息  状态变成 认证中
        sysUser.setAuthStatus("3");
        sysUserService.updateById(sysUser);


        // 判断当前用户类型是不是和原来的级别相等或者大于原来的等级
        String now = bo.getUserType().substring(1);
        String yuanlai = sysUser.getUserType().substring(1);
        AssertUtils.isTrue(Integer.valueOf(now) >= Integer.valueOf(yuanlai), "只能提升等级,不能降低");

        AssertUtils.isTrue(IdcardUtil.isValidCard(bo.getCardNo()), "身份证号不合法");
        TbUserJoinOrder tbUserJoinOrder = BeanUtil.copyProperties(bo, TbUserJoinOrder.class);

        // 身份没有做改变
        if (sysUser.getUserType().equals(bo.getUserType())) {
            // 已支付状态
            tbUserJoinOrder.setOrderStatus(UserJoinOrderOrderStatusEnum.YIZHIFU.getValue());
            tbUserJoinOrder.setPhoneNumber(sysUser.getPhoneNumber());

        } else {

//            String now = bo.getUserType().substring(1);
//            String yuanlai1 = sysUser.getUserType().substring(1);
//            if (Integer.valueOf(now) > Integer.valueOf(yuanlai1)) {
//                tbUserJoinOrder.setOrderStatus(UserJoinOrderOrderStatusEnum.WEIZHIFU.getValue());
//            } else if (Integer.valueOf(now) == Integer.valueOf(yuanlai1)) {
            tbUserJoinOrder.setOrderStatus(UserJoinOrderOrderStatusEnum.YIZHIFU.getValue());
            // }
        }
        // 查询原来的申请记录
        TbUserJoinOrder yuanlaide = getOne(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getOrderStatus,
                        UserJoinOrderOrderStatusEnum.SHENHETONGGUO.getValue()).eq(TbUserJoinOrder::getUserId, sysUser.getUserId())
                .orderByDesc(TbUserJoinOrder::getCreateTime).last("limit 1"));

        tbUserJoinOrder.setInviteCode(yuanlaide.getInviteCode());
        tbUserJoinOrder.setPassword(yuanlaide.getPassword());
        tbUserJoinOrder.setWxAvatar(sysUser.getAvatar());
        tbUserJoinOrder.setWxCode(sysUser.getWxUid());
        tbUserJoinOrder.setWxNickName(sysUser.getNickName());


        BigDecimal orderPrice = BigDecimal.ZERO;
        if (bo.getUserType().equals(UserTypeEnum.ZHUBO.getValue())) {
            orderPrice = new BigDecimal(sysConfigService.selectConfigByKey("zhubo_price"));
        } else if (bo.getUserType().equals(UserTypeEnum.TUANZHANG.getValue())) {
            orderPrice = new BigDecimal(sysConfigService.selectConfigByKey("tuanzhang_price"));
        } else if (bo.getUserType().equals(UserTypeEnum.FENGONGSI.getValue())) {
            orderPrice = new BigDecimal(sysConfigService.selectConfigByKey("fengongsi_price"));
        }

        // 订单金额
        tbUserJoinOrder.setOrderPrice(orderPrice);


        // 生成订单编号
        String format = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        String numbers = RandomUtil.randomNumbers(5);
        String orderNo = "AP" + format + numbers;
        tbUserJoinOrder.setOrderNo(orderNo);

        tbUserJoinOrder.setUserId(sysUser.getUserId());

        save(tbUserJoinOrder);


        // 抖音号列表
        List<AppTbUserJoinOrderDetailAddBo> tiktokList = bo.getTiktokList();
        List<TbUserJoinOrderDetail> tiktoks = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(tiktokList)) {
            for (AppTbUserJoinOrderDetailAddBo appTbUserTiktokAddBo : tiktokList) {
                TbUserJoinOrderDetail tbUserJoinOrderDetail = BeanUtil.copyProperties(appTbUserTiktokAddBo, TbUserJoinOrderDetail.class);

                // 查询抖音uid是不是已经绑定到其他用户名下
                long count = tbUserTiktokService.count(Wrappers.lambdaQuery(TbUserTiktok.class).eq(TbUserTiktok::getTikUid,
                        tbUserJoinOrderDetail.getTikUid()).ne(TbUserTiktok::getUserId, sysUser.getUserId()));

                AssertUtils.isTrue(count == 0, "抖音uid【" + tbUserJoinOrderDetail.getTikUid() + "】,已被其他用户绑定,不能重复绑定");

                tbUserJoinOrderDetail.setJoinOrderId(tbUserJoinOrder.getId());
                tiktoks.add(tbUserJoinOrderDetail);
            }
            if (ObjectUtil.isNotEmpty(tiktoks)) {
                tbUserJoinOrderDetailService.saveAll(tiktoks);
            }
        }

//        if (ObjectUtil.isNotEmpty(bo.getUserType())) {
//
//
//            // 判断当前用户类型比之前的身份大才需要支付
//            String now = bo.getUserType().substring(1);
//            String yuanlai1 = sysUser.getUserType().substring(1);
//            if (Integer.valueOf(now) > Integer.valueOf(yuanlai1)) {
//
//                // 应付金额转换为分
//                int fen = orderPrice.movePointRight(2).intValue();
//
//                Payer payer = new Payer();
//                payer.setOpenid(sysUser.getWxUid());
//                UnifiedOrderModel unifiedOrderModel = new UnifiedOrderModel()
//                        .setAppid(wxPayV3Bean.getAppId())
//                        .setMchid(wxPayV3Bean.getMchId())
//                        .setDescription("用户入驻")
//                        .setOut_trade_no(orderNo)
//                        .setAttach("微信支付方式支付")
//                        .setNotify_url(wxPayV3Bean.getDomain().concat(wxPayV3Bean.getNotifyUrl()))
//                        .setAmount(new Amount().setTotal(fen))
//                        .setPayer(payer);
//
//                log.info("统一下单参数 {}", JSONUtil.toJsonStr(unifiedOrderModel));
//
//                IJPayHttpResponse response = WxPayApi.v3(
//                        RequestMethod.POST,
//                        WxDomain.CHINA.toString(),
//                        WxApiType.JS_API_PAY.toString(),
//                        wxPayV3Bean.getMchId(),
//                        getSerialNumber(),
//                        null,
//                        wxPayV3Bean.getKeyPath(),
//                        JSONUtil.toJsonStr(unifiedOrderModel)
//                );
//                log.info("统一下单响应 {}", response);
//
//                // 根据证书序列号查询对应的证书来验证签名结果
//
//                JSONObject entries = JSONUtil.parseObj(response.getBody());
//                String prepayId = entries.getStr("prepay_id");
//                log.info("预支付的id为--------》{}", prepayId);
//                Map<String, String> orderMap = WxPayKit.jsApiCreateSign(wxPayV3Bean.getAppId(), prepayId, wxPayV3Bean.getKeyPath());
//                appTbUserJoinOrderVo.setOrderInfo(orderMap);
//            }
//
//        }

        appTbUserJoinOrderVo.setNeedPay("2");

        return appTbUserJoinOrderVo;
    }


    @Override
    public AppTbUserJoinOrderInfoVo join(AppTbUserJoinOrderQueryBo bo) throws Exception {

        AppTbUserJoinOrderInfoVo joinOrderVo = getVoOne(Wrappers.lambdaQuery(TbUserJoinOrder.class).eq(TbUserJoinOrder::getPhoneNumber,
                bo.getPhoneNumber()).orderByDesc(TbUserJoinOrder::getCreateTime).last("limit 1"), AppTbUserJoinOrderInfoVo.class);

        if (ObjectUtil.isNotEmpty(joinOrderVo)) {
            // 查询入住详情
            List<AppTbUserJoinOrderDetailVo> appTbUserJoinOrderDetailVos = tbUserJoinOrderDetailService.
                    listVo(Wrappers.lambdaQuery(TbUserJoinOrderDetail.class).eq(TbUserJoinOrderDetail::getJoinOrderId, joinOrderVo.getId()),
                            AppTbUserJoinOrderDetailVo.class);

            joinOrderVo.setDetailList(appTbUserJoinOrderDetailVos);


        }
        return joinOrderVo;
    }
}
